
import {getNameFromUrl} from '../../utils/util'

const app = getApp()

Page({
  onShareAppMessage() {
    return {
      title: 'editor',
      path: 'page/component/pages/editor/editor'
    }
  },
  data: {
    article: 0,   //当前文章id
    family: 0,   //当前所属家族
    formats: {},
    readOnly: false,
    placeholder: '开始输入...',
    editorHeight: 300,
    keyboardHeight: 0,
    isIOS: false,
    safeHeight: 0,
    toolBarHeight: 50,
    last_delta: {},  //上一次的改动
    last_html: '',  //上一次改动对应的html
    has_unsaved: false,  //是否有编辑内容没有保存
    has_saved: false,  //是否保存过
    online_pic_names: [],  //在线图片的图片名，根据它来区分是新上传图片还是已上传图片。
  },
  readOnlyChange() {
    this.setData({
      readOnly: !this.data.readOnly
    })
  },
  onLoad(options) {
    //这里一般比editor ready提前
    this.setData({
      article: parseInt(options.article),
      family: parseInt(options.family)
    })

    const { platform, safeArea, model, screenHeight} = wx.getSystemInfoSync()
    let safeHeight;
    if (safeArea) {
      safeHeight = (screenHeight - safeArea.bottom);
    } else  {
      safeHeight = 32;
    }
    this._safeHeight = safeHeight;
    let isIOS = platform === 'ios'
    this.setData({ isIOS, safeHeight, toolBarHeight: isIOS ? safeHeight + 50 : 50 })
    const that = this
    this.updatePosition(0)
    let keyboardHeight = 0
    wx.onKeyboardHeightChange(res => {
      if (res.height === keyboardHeight) {
        return
      }      
      const duration = res.height > 0 ? res.duration * 1000 : 0
      keyboardHeight = res.height
      setTimeout(() => {
        wx.pageScrollTo({
          scrollTop: 0,
          success() {
            that.updatePosition(keyboardHeight)
            that.editorCtx.scrollIntoView()
          }
        })
      }, duration)

    })
  },
  updatePosition(keyboardHeight) {
    const toolbarHeight = 50
    const { windowHeight, platform } = wx.getSystemInfoSync()
    let editorHeight = keyboardHeight > 0 ? (windowHeight - keyboardHeight - toolbarHeight) : windowHeight
    if (keyboardHeight === 0) {
      this.setData({
        editorHeight, keyboardHeight,
        toolBarHeight: this.data.isIOS ? 50 + this._safeHeight : 50,
        safeHeight: this._safeHeight,
      })
    } else {
      this.setData({ editorHeight, keyboardHeight, 
        toolBarHeight: 50,
        safeHeight: 0, 
      })
    }
  },
  calNavigationBarAndStatusBar() {
    const systemInfo = wx.getSystemInfoSync()
    const { statusBarHeight, platform } = systemInfo
    const isIOS = platform === 'ios'
    const navigationBarHeight = isIOS ? 44 : 48
    return statusBarHeight + navigationBarHeight
  },
  onEditorReady() {
    wx.createSelectorQuery().select('#editor').context(res => {
      console.log('aaaaaaa')
      this.editorCtx = res.context

      app.httpRequest('get_family_article_info', {
        article: this.data.article,
        family: this.data.family
      }, res => {
        console.log('get_family_article_info succ: ', res)
        //先设置页面标题
        wx.setNavigationBarTitle({
          title: res.title
        })
        let json = JSON.parse(res.content_delta)
        this.setData({
          last_delta: json
        })

        this.editorCtx.setContents({
          "delta": json,
          success: () => {
            //注意： 此处可以将delta转化为html或text
            let data = this.editorCtx.getContents({
              success: e => {
                console.log('first get contents', e)
                this.setData({
                  last_html: e.html
                })
                this.GetOnLinePicNamesFromDelta(e.delta)  //记录当前线上图片
              }
            })
          },
          fail: () => {
            console.log('eeeeeeeeeeeeeee')
          }
        })

      }, res => {
        console.log('get_family_article_info fail: ', res)
        wx.setNavigationBarTitle({
          title: '个人文章'
        })
      })

    }).exec()
  },
  //从delta数据中获取在线图片名
  GetOnLinePicNamesFromDelta(delta) {
    let pic_names = []
    let ops = delta.ops || []
    for (let i = 0; i < ops.length; i++) {
      if (typeof(ops[i].insert) == "object" && ops[i].insert.image && ops[i].insert.image.length > 0) {
        let name = getNameFromUrl(ops[i].insert.image)
        if (name.length > 0) {
          pic_names.push(name)
        }
      }
    }
    this.setData({
      online_pic_names: pic_names
    })
  },
  blur() {
    this.editorCtx.blur()
  },
  format(e) {
    let { name, value } = e.target.dataset
    if (!name) return
    // console.log('format', name, value)
    this.editorCtx.format(name, value)

  },
  onStatusChange(e) {
    const formats = e.detail
    this.setData({ formats })
  },
  insertDivider() {
    this.editorCtx.insertDivider({
      success: function () {
        console.log('insert divider success')
      }
    })
  },
  clear() {
    this.editorCtx.clear({
      success: function (res) {
        console.log("clear success")
      }
    })
  },
  removeFormat() {
    this.editorCtx.removeFormat()
  },
  insertDate() {
    const date = new Date()
    const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.editorCtx.insertText({
      text: formatDate
    })
  },
  insertImage() {

    wx.chooseImage({
      count: 1,
      success: res => {
        this.editorCtx.insertImage({
          src: res.tempFilePaths[0],
          data: {
            id: 'abcd',
            role: 'god'
          },
          width: '80%',
          success: function () {
            console.log('insert image success')
          }
        })
      }
    })
  },

  //判断delta是否为空
  isDeltaEmpty(delta) {
    let ops = delta.ops || []
    if (ops.length == 0) {
      return true
    } else if (ops.length == 1) {
      if (ops[0].insert == "\n") {
        return true
      }
    } else {
      return false
    }
  },

  onEditorInput(e) {
    //console.log('++++++++++++', JSON.stringify(e.detail))
    this.setData({
      last_delta: e.detail.delta,
      last_html: e.detail.html
    })

    if (!this.data.has_unsaved) {
      this.setData({
        has_unsaved: true
      })
      //退出前提示有内容未保存，PC端暂不支持
      wx.enableAlertBeforeUnload({
        message: '有编辑内容未保存，确定返回吗？'
      })
    }
  },
  bindTapUndo(e) {
    //console.log('undo----', e)
    if (this.editorCtx) {
      this.editorCtx.undo()
    }
  },
  bindTapRedo(e) {
    if (this.editorCtx) {
      this.editorCtx.redo()
    }
  },

  calcImageNumfromOps(ops) {
    let imageNum = 0;
    for (let i = 0; i < ops.length; i++) {
      if (typeof(ops[i].insert) == "object" && typeof(ops[i].insert.image) == "string") {
        imageNum++
      }
    }
    return imageNum
  },

  bindTapSave(e) {
    //保存数据
    let delta = this.data.last_delta
    let ops = delta.ops || []

    if (JSON.stringify(ops).length > 10000) {
      app.showTip('文章内容太长，无法保存')
      return
    }
    if (this.calcImageNumfromOps(ops) > 100) {
      app.showTip('一篇文章中的图片不能超过100个')
      return
    }

    //解析要上传的线下图片
    let to_upload_images = []
    let to_upload_cache = {}   //下标 -> 图片
    for (let i = 0; i < ops.length; i++) {
      if (typeof(ops[i].insert) == "object" && ops[i].insert.image && ops[i].insert.image.length > 0) {
        //图片
        let image = ops[i].insert.image
        let name = getNameFromUrl(image)  //获取图片名字
        if (this.data.online_pic_names.includes(name)) {
          //线上图片
        } else {
          //线下图片
          to_upload_images.push(image)
          to_upload_cache[i] = getNameFromUrl(image)
        }
      }
    }

    //上传图片
    var length = to_upload_images.length; //总数
    if (length > 9) {
      app.showTip("一次最多上传9张图片！")
    }
    if (length > 0) {
      var count = 0; //第几张
      this.uploadOneByOne(to_upload_images, count, length, 
      () => {
        //上图图片成功，开始保存文章
        this.saveArticleInfo(delta, to_upload_cache)
      }, () => {
        //失败
        app.showTip("上传图片失败，请联系管理员")
      })
    } else {
      //没有新图片，直接保存文章
      this.saveArticleInfo(delta, {})
    }
    
  },

  //上传图片后保存文章，参数to_upload_cache： ops下标 -> 本次上传图片名
  saveArticleInfo(delta, to_upload_cache) {
    console.log('to save article:', delta, to_upload_cache)
    app.httpRequest('edit_family_article_info', {
      article: this.data.article,
      family: this.data.family,
      local_images: to_upload_cache,  //本次保存上传的图片
      delta: JSON.stringify(delta)
    }, res => {
      console.log('upload article success: ', res)
      this.setData({
        has_saved: true
      })
      this.GetOnLinePicNamesFromDelta(delta)  //记录当前线上图片

      if (this.data.has_unsaved) {
        this.setData({
          has_unsaved: false
        })
        wx.disableAlertBeforeUnload()  //关闭返回提醒
      }

    }, res => {
      console.log('upload article failed: ', res)
    })
  },

  /**
  * 采用递归的方式上传多张, 注意wx.uploadFile不能并发, 还有ui不支持一次上传同时显示成功和失败，所以此函数要么成功，要么失败
  */
 uploadOneByOne(imgPaths, count, length, allSuccCallback, allFailCallback){
    var scope = this;
    wx.uploadFile({
      url: app.globalConfig.getPicEditUrl() + '/file/upload', //仅为示例，非真实的接口地址
      filePath: imgPaths[count],
      name: 'file',
      formData: {
        'key': 'val'
      },
      success:function(e){
        count++;//下一张
        if(count == length){
          //上传完毕，作一下提示
          allSuccCallback()
        }else{
          //递归调用，上传下一张
          scope.uploadOneByOne(imgPaths, count, length, allSuccCallback, allFailCallback);
        }
      },
      fail:function(e){
        //失败了，所有图片都发送失败，删除之前已经发送的
        for (let i = 0; i < count; i++) {
          scope.requestDeletePic(imgPaths[i])
        }
        allFailCallback()
      }
    })
  },

  //从后台删除图片
  requestDeletePic(url) {
    let filename = getNameFromUrl(url)
    if (filename == '') {
      return
    }
    
    wx.request({
      url: app.globalConfig.getPicEditUrl() + '/file/delete',
      method: 'POST',
      header: { 'content-type': 'application/x-www-form-urlencoded'},
      data: {
        filename: filename
      },
      success: (res) => {
        console.log('delete file success!')
      },
      fail: (res) => {
        console.log('delete file failed!')
      }
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //返回
    //如果有保存过就刷新前一个页面
    if (this.data.has_saved) {
      let pages = getCurrentPages()  //获取当前页面js里面的pages里的所有信息。
      let prevPage = pages[pages.length - 2]  //prevPage 是获取上一个页面的js里面的pages的所有信息。 -2 是上一个页面，-3是上上个页面以此类推。
      
      if (prevPage.BeginLoadArticles) {
        //返回列表页面
        prevPage.BeginLoadArticles()
      } else if (prevPage.loadArticle) {
        //返回展示页面
        prevPage.loadArticle()
        prevPage.setData({
          has_edit: true
        })
      }
    }

  },
})
